import urls     from './urls'
import get      from './get'
import {post,postJson}     from './post'
import form     from './form'
import validate from './validate'
import {fromJS} from 'immutable'
import msg from '../components/Message'
import dialog from '../components/dialog'
import loading from '../components/loading'
const userAgent = window.navigator.userAgent
const isAndroid = userAgent.indexOf('Android') > -1
const isIos     = userAgent.indexOf('iPhone') > -1
const isWin     = isIos||isAndroid ? false : true // 区分电脑版微信，不是安卓，苹果手机


const utils={
  version   : '1.1.0',
  height    : window.screen.height,
  width     : window.screen.width,
  url       : urls,
  get       : get,
  post      : post,
  form      : form,
  msg : (obj)=>{
    msg.info(obj.text,obj.code)
  },
  dialog, // 弹出对话框
  postJson,
  validate,
  cacheData:{}, // 本地的一些缓存数据
  sortObject(obj){   //对json数据对属性进行排序
      // 先获取所有属性名
      var keys = [];
      for (var key in obj)
      {
          keys.push(key);
      }
      // 排序
      keys.sort();
      // 导出新的对象
      var r = {};
      for (var i = 0; i < keys.length; i++)
      {
          key = keys[i];
          r[key] = obj[key];
      }
      return r;
  },
  getCookie:function(key){//获取cookie方法
    /*获取cookie参数*/
    var getCookie = document.cookie.replace(/[ ]/g,"");  //获取cookie，并且将获得的cookie格式化，去掉空格字符
    var arrCookie = getCookie.split(";")  //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
    var tips;  //声明变量tips
    for(var i=0;i<arrCookie.length;i++){   //使用for循环查找cookie中的tips变量
      var arr=arrCookie[i].split("=");   //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
      if(key==arr[0]){  //匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
        tips=arr[1];   //将cookie的值赋给变量tips
        break;   //终止for循环遍历
      } 
    }
    return tips;
  },
  humanTime:(input)=>{
    function pad(d) {
      return (d < 10) ? '0' + d.toString() : d.toString();
    }

    var min = (input / 60) << 0,
        sec = Math.round((input) % 60);

    return pad(min) + ':' + pad(sec);
  },
  buildScorll:function(el){
    return new IScroll(el, {
      mouseWheel: true,
      click : !isWin, // isWin==true 电脑版微信时，click:false ,兼容触发两个次点击 
      // tap   : true,
      scrollX : false, 
      freeScroll: true ,
      probeType : 2,
      preventDefault : true
    });
  },
  number(num,digit){
    digit = digit === undefined ? 2 : +digit;
    return Number(num).toFixed(digit)
  },
  numberToPrice(num, options = {
    showDecimals:2,// 格式化小数位
    showSymbol : true
  }) {
    const showSymbol = options.showSymbol;
    const showDecimals = options.showDecimals;
    // console.log(showDecimals)
    return num.toLocaleString('zh', {
      style: showSymbol ? 'currency' : undefined,
      currency: showSymbol ? 'CNY' : undefined,
      maximumFractionDigits: showDecimals,
    });
  },
  /* 
    根据id获取在数组中的索引下标
    返回索引下标
  */
  getIndexById(list,item){
    if(!Array.isArray(list)){
      console.error('list is not an Array')
      return -1;
    }
    for(let i = 0;i<list.length;i++){
      if( (list[i].id && item.id === list[i].id) || (list[i]===item.id)) {
        return i;
      }
    }
    return -1
  },

  removeItemById(list,id){
    list = fromJS(list).toJS()
    // list = _.cloneDeep(list)
    if(!Array.isArray(list)){
      console.error('list is not an Array')
      return -1;
    }
    var index = -1;
    for(let i = 0;i<list.length;i++){
      if(list[i].id&&id === list[i].id){
        index = i;
        break
      }else{
        if(list[i] === id){
          index = i;
          break
        }
      }
    }
    if(index > -1){
      list.splice(index,1);
    } 
    return list;
  },
  removeItemByIndex(list,id){
    if(!Array.isArray(list)){
      console.error('list is not an Array')
      return -1;
    }
    for(let i = 0;i<list.length;i++){
      if((list[i].id&&id === list[i].id)||(list[i] === id)){
        list.splice(i,1);
        return list;
      }
    }
    return list;
  },
  // cloneDeep(obj){
  //   return _.cloneDeep(obj)
  // },
  onValidNumber(number){
    let re = /^\d+$/
    let num = number
    if(!re.test(num) || num == '' || num==null || num ==undefined){
      num = 0;
    }
    return num
  },
  // 乘法  
  accMul (arg1,arg2)   {   
    var m=0,s1=arg1.toString(),s2=arg2.toString();   
    try{m+=s1.split(".")[1].length}catch(e){}   
    try{m+=s2.split(".")[1].length}catch(e){}   
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)   
  },
  // 加法
  accAdd (arg1,arg2){   
    var r1,r2,m;   
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}   
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}   
    m=Math.pow(10,Math.max(r1,r2));
    var n=Math.max(r1,r2);
            n>2?n=2:n;/*money最多保留两位小数*/  
    return ((arg1*m+arg2*m).toFixed(n))/m   
  } ,
  buildParams(params){
    var str = ''
    for(var key in params){
      str += key+'='+params[key]+"&"
    }
    str = str.substr(0,str.length-1)
    return "?"+str
  },
  runGenerator (generator) {
    var it = generator();
    function go(result) {
      if (result.done) return result.value;
      if(result.value.then){ // Promise对象回调
        return result.value.then(function (value) {
          return go(it.next(value));
        }, function (error) {
          return go(it.throw(error));
        }); 
      }else if(typeof result.value=='function'){ 
        result.value(function(ret){
          console.log(ret)
          return go(it.next(ret))
        })
      }
    }
    go(it.next());
  },
  //加密
  encrypt_js(content){
    var crypt_key = '59b6ab46d379b89d794c87b74a511fbd59b6ab46d379b89d794c87b74a511fbd';
    var shaObj = new jsSHA("SHA-1", "TEXT");
    if(shaObj) {
        shaObj.update(crypt_key);
        var result = shaObj.getHash("HEX");
        result = result.toLocaleUpperCase();
        result = result.substr(0, 32);
    //    console.log(result);
        var key = crypt_key;//result;
        var iv = '0aaff094b6dc29742cc98a4bac8bc8f9'; //result;
        /*var key = CryptoJS.enc.Latin1.parse(result);
         var iv = CryptoJS.enc.Latin1.parse(result);*/
        var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(content), CryptoJS.enc.Hex.parse(key), { iv: CryptoJS.enc.Hex.parse(iv) });

        return encrypted.ciphertext.toString();
    }
    return null;
}
  

}
module.exports = utils












